package com.example.xianji.activity;

import java.io.InputStream;
import java.net.URL;
import java.text.SimpleDateFormat;

import org.json.JSONException;
import org.json.JSONObject;

import com.example.xianji.Contant;
import com.example.xianji.R;
import com.example.xianji.widgets.CustomProgressDialog;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;

import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.os.Build.VERSION;
import android.os.Build.VERSION_CODES;
import android.app.Activity;
import android.graphics.drawable.Drawable;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

public class Main_Forget_PassWordActivity extends Activity implements OnClickListener {
    private EditText edittext_phone, tuxing_yanzheng, editText_password, editText_queren_password, editText_yanzhengma;
    private Drawable d;
    private ImageView forget_imageview, forgrt_password_back;
    private Button forget_yanzheng, forgetpassword_tijiao;
    private TimeCount mTimeCount;
    private CustomProgressDialog mCustomProgressDialog;
    private String phone;
    private Handler handle = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 1) {
                forget_imageview.setImageDrawable(d);
            }
            if (msg.what == 2) {
                if (mCustomProgressDialog != null) {
                    mCustomProgressDialog.dismiss();
                    mCustomProgressDialog = null;
                }
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (VERSION.SDK_INT >= VERSION_CODES.KITKAT) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        }
        setContentView(R.layout.activity_main__forget__pass_word);
        //XJApplication.getInstance().addActivity(this);
        edittext_phone = (EditText) findViewById(R.id.edittext_phone);
        forget_imageview = (ImageView) findViewById(R.id.forget_imageview);
        forget_yanzheng = (Button) findViewById(R.id.forget_yanzheng);
        mTimeCount = new TimeCount(60000, 1000);
        tuxing_yanzheng = (EditText) findViewById(R.id.tuxing_yanzheng);
        forgetpassword_tijiao = (Button) findViewById(R.id.forgetpassword_tijiao);
        editText_password = (EditText) findViewById(R.id.editText_password);
        editText_queren_password = (EditText) findViewById(R.id.editText_queren_password);
        editText_yanzhengma = (EditText) findViewById(R.id.editText_yanzhengma);
        forgrt_password_back = (ImageView) findViewById(R.id.forgrt_password_back);

        edittext_phone.addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.toString().length() == 11) {
                    phone = s.toString();

                    new Thread(new Runnable() {

                        @Override
                        public void run() {
                            LoadImageFromWebOperations(Contant.tuxing_yanzheng + phone);
                        }
                    }).start();
                }
            }
        });

        forget_yanzheng.setOnClickListener(this);
        forgetpassword_tijiao.setOnClickListener(this);
        forgrt_password_back.setOnClickListener(this);
    }

    /**
     * 通过URL加载ImageView
     *
     * @param url
     * @return
     */
    private Drawable LoadImageFromWebOperations(String url) {
        try {
            InputStream is = (InputStream) new URL(url).getContent();
            d = Drawable.createFromStream(is, "src name");
            handle.sendEmptyMessage(1);
            return d;
        } catch (Exception e) {
            System.out.println("Exc=" + e);
            return null;
        }
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.forget_yanzheng) {
            if (tuxing_yanzheng.getText().toString().length() > 0) {
                mTimeCount.start();
                huoqu_yanzhengma();
            } else {
                Toast.makeText(Main_Forget_PassWordActivity.this, "请填写图形验证", 0).show();
            }

        } else if (v.getId() == R.id.forgetpassword_tijiao) {
            if (editText_yanzhengma.getText().toString().length() > 0) {
                if (editText_password.getText().toString().length() > 0) {
                    mCustomProgressDialog = CustomProgressDialog.createDialog(getApplicationContext());
                    mCustomProgressDialog.setCanceledOnTouchOutside(false);
                    mCustomProgressDialog.show();
                    tijiao_new_password();
                } else {
                    Toast.makeText(Main_Forget_PassWordActivity.this, "请输入新密码", 0).show();
                }
            } else {
                Toast.makeText(Main_Forget_PassWordActivity.this, "请输入手机验证码", 0).show();
            }
        } else if (v.getId() == R.id.forgrt_password_back) {
            this.finish();
        }
    }

    /**
     * 获取短信验证
     */
    public void huoqu_yanzhengma() {
        HttpUtils httpUtils = new HttpUtils();
        RequestParams parms = new RequestParams();
        parms.addBodyParameter("code_from", "resetpwd");
        parms.addBodyParameter("mobile", edittext_phone.getText().toString());
        parms.addBodyParameter("picverify", tuxing_yanzheng.getText().toString());
        httpUtils.send(HttpMethod.POST, Contant.message_yanzheng, parms, new RequestCallBack<String>() {

            @Override
            public void onFailure(HttpException arg0, String arg1) {
            }

            @Override
            public void onSuccess(ResponseInfo<String> arg0) {
                try {
                    JSONObject obj = new JSONObject(arg0.result);
                    Toast.makeText(Main_Forget_PassWordActivity.this, obj.getString("msg"), 0).show();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public void tijiao_new_password() {
        HttpUtils httpUtils = new HttpUtils();
        RequestParams parms = new RequestParams();
        parms.addBodyParameter("password", editText_password.getText().toString());
        parms.addBodyParameter("password_confirmation", editText_queren_password.getText().toString());
        parms.addBodyParameter("mverify", editText_yanzhengma.getText().toString());
        parms.addBodyParameter("mobile", edittext_phone.getText().toString());
        parms.addBodyParameter("picverify", tuxing_yanzheng.getText().toString());
        httpUtils.send(HttpMethod.POST, Contant.forget_password, parms, new RequestCallBack<String>() {

            @Override
            public void onFailure(HttpException arg0, String arg1) {
                if (mCustomProgressDialog != null) {
                    mCustomProgressDialog.dismiss();
                    mCustomProgressDialog = null;
                }
            }

            @Override
            public void onSuccess(ResponseInfo<String> arg0) {
                try {
                    JSONObject obj = new JSONObject(arg0.result);
                    if (obj.getInt("status") == 1) {
                        Toast.makeText(Main_Forget_PassWordActivity.this, obj.getString("msg"), 0).show();
                        Main_Forget_PassWordActivity.this.finish();
                    } else {
                        Toast.makeText(Main_Forget_PassWordActivity.this, obj.getString("msg"), 0).show();
                    }
                    handle.sendEmptyMessage(2);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        handle.removeCallbacksAndMessages(null);
    }

    class TimeCount extends CountDownTimer {
        public TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onFinish() {
            forget_yanzheng.setText("重新获取");
            forget_yanzheng.setBackgroundColor(getResources().getColor(R.color.blue22));
        }

        @Override
        public void onTick(long millisUntilFinished) {
            String str = new SimpleDateFormat("ss").format(Long.valueOf(millisUntilFinished));
            if (str.equals("00")) {
                forget_yanzheng.setText("60秒");
            }
            forget_yanzheng.setText(str + "秒");
            forget_yanzheng.setBackgroundColor(getResources().getColor(R.color.gray98));
        }
    }
}
